<template>
  <div class="zero-code-list">
    <a-spin :spinning="grid.loading">
      <vxe-grid v-if="!grid.loading" v-bind="grid" :ref="record.key">
        <template #toolbar_buttons>
          <a-button
            type="link"
            icon="plus"
            @click="add"
            v-if="record.options.canAdd"
          >
            新增
          </a-button>
          <a-button type="link" icon="edit" v-if="record.options.canEdit">
            编辑</a-button
          >

          <a-button
            @click="chosenClick"
            type="link"
            v-if="record.options.canDelete"
          >
            <a-icon type="shrink"></a-icon>
            <span> 关联已有 </span>
          </a-button>
          <a-popconfirm
            title="确定取消关联数据?"
            ok-text="确定"
            cancel-text="取消"
            v-if="record.options.canDelete"
            @confirm="clear"
          >
            <a-button type="link">
              <a-icon type="arrows-alt" style="color: #ff4d4f"></a-icon>
              <span class="text-red"> 取消关联 </span>
            </a-button>
          </a-popconfirm>
          <a-popconfirm
            ok-text="删除记录"
            cancel-text="仅取消关联关系"
            v-if="record.options.canDelete"
            @confirm="remove(row)"
          >
            <template slot="title">
              <div
                class="mui-dialog-default-title"
                style="color: #151515; font-size: 17px; font-weight: 600"
              >
                <div style="font-weight: bold; color: rgb(244, 67, 54)">
                  注意：此操作将删除原始记录
                </div>
              </div>
              <br />
              <div class="mui-dialog-desc">
                如果只需要取消与当前记录的关联关系，<br />仍保留原始记录。可以选择仅取消关联关系
              </div>
            </template>
            <a-button type="link" v-if="record.options.canDelete">
              <a-icon type="delete" style="color: #ff4d4f"></a-icon>
              <span class="text-red"> 删除 </span>
            </a-button>
          </a-popconfirm>
          <a-dropdown v-if="record.options.canReport">
            <a-menu slot="overlay">
              <a-menu-item key="1">
                <a-icon type="file-excel" />导出记录(excel)
              </a-menu-item>
              <a-menu-item key="2">
                <a-icon type="file-zip" />导出附件
              </a-menu-item>
              <a-menu-item key="3">
                <a-icon type="file-pdf" />导出PDF
              </a-menu-item>
            </a-menu>
            <a-button type="link" icon="download">
              导出
              <a-icon type="down" />
            </a-button>
          </a-dropdown>
        </template>
        <template #toolbar_tools> </template>
        <template #loading>
          <a-spin></a-spin>
        </template>
        <template #empty>
          <eip-empty />
        </template>
        <template #checkboxHeader="{ checked, indeterminate }">
          <span @click.stop="$refs[record.key].toggleAllCheckboxRow()">
            <a-checkbox :indeterminate="indeterminate" :checked="checked">
            </a-checkbox>
          </span>
        </template>
        <template #checkbox="{ row, checked, indeterminate }">
          <span @click.stop="$refs[record.key].toggleCheckboxRow(row)">
            <a-checkbox :indeterminate="indeterminate" :checked="checked">
            </a-checkbox>
          </span>
        </template>

        <template #operate="{ row }">
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item key="1">
                <a-popconfirm
                  title="你确定要取消关联吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  v-if="record.options.canDelete"
                  @confirm="remove(row)"
                >
                  <a-icon type="arrows-alt" style="color: #ff4d4f"></a-icon>
                  <span class="text-red"> 取消关联 </span>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-divider />
              <a-menu-item key="2">
                <a-tooltip title="" v-if="record.options.canEdit">
                  <a-icon type="edit" class="eip-cursor-pointer"></a-icon
                  >编辑</a-tooltip
                >
              </a-menu-item>
              <a-menu-item key="3">
                <a-popconfirm
                  ok-text="删除记录"
                  cancel-text="仅取消关联关系"
                  v-if="record.options.canDelete"
                  @confirm="remove(row)"
                >
                  <template slot="title">
                    <div
                      class="mui-dialog-default-title"
                      style="color: #151515; font-size: 17px; font-weight: 600"
                    >
                      <div style="font-weight: bold; color: rgb(244, 67, 54)">
                        注意：此操作将删除原始记录
                      </div>
                    </div>
                    <br />
                    <div class="mui-dialog-desc">
                      如果只需要取消与当前记录的关联关系，<br />仍保留原始记录。可以选择仅取消关联关系
                    </div>
                  </template>
                  <a-icon type="delete" style="color: #ff4d4f"></a-icon>
                  <span class="text-red"> 删除 </span>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
            <a-icon type="more" :rotate="90" />
          </a-dropdown>
        </template>
        <!-- 序号 -->
        <template #seq="">
          <span>序号</span>
        </template>
        <template #edit="{ row, column }">
          <div
            v-for="(record, index) in columns.filter(
              (f) =>
                record.options.columns.includes(f.key) && column.field == f.key
            )"
            :key="index"
          >
            <component
              :is="'e' + record.type"
              :column="column"
              :row="row"
              :record="record"
              :isEdit="true"
              @change="updateStatus({ row, column })"
            ></component>
          </div>
        </template>
        <!-- 格式化内容 -->
        <template #default="{ record, column }">
          <div
            v-for="(item, index) in columns.filter(
              (f) =>
                record.options.columns.includes(f.key) && column.field == f.key
            )"
            :key="index"
          >
            <component
              :is="'e' + item.type"
              :column="column"
              :record="record"
              :item="item"
              :isEdit="false"
            ></component>
          </div>
        </template>
      </vxe-grid>
    </a-spin>
    <!-- 表单 -->
    <worksheet-run
      ref="worksheetRun"
      v-if="worksheetRun.visible"
      :visible.sync="worksheetRun.visible"
      :options="{
        rowId: worksheetRun.rowId,
        rowIds: [worksheetRun.rowId],
        zeroCodeId: record.options.zeroCodeId,
        mode: eipZeroCodeWorkSheetMode.add,
        from: {
          zeroCodeId: worksheet.zeroCodeId,
          key: record.key, //来源控件
          rowId: worksheet.rowId, //来源数据RowId
        },
      }"
      @ok="worksheetRunOk"
    ></worksheet-run>
    <!-- 表格数据选择 -->
    <grid-chosen
      ref="gridchosen"
      v-if="chosen.visible"
      :visible.sync="chosen.visible"
      :record="record"
      :from="{
        zeroCodeId: worksheet.zeroCodeId,
        key: record.key, //来源控件
        rowId: worksheet.rowId, //来源数据RowId
        rowIds: chosen.rowIds,
      }"
      @ok="chosenOk"
    ></grid-chosen>
  </div>
</template>
<script>
import { newGuid } from "@/utils/util";
import gridInput from "./../../grid/input.vue";
import gridTextarea from "./../../grid/textarea.vue";
import gridSwitch from "./../../grid/switch.vue";
import gridNumber from "./../../grid/number.vue";
import gridRadio from "./../../grid/radio.vue";
import gridSelect from "./../../grid/select.vue";
import gridCheckbox from "./../../grid/checkbox.vue";
import gridSys from "./../../grid/sys.vue";
import gridSerialNo from "./../../grid/serialNo.vue";
import gridDate from "./../../grid/date.vue";
import gridOtherField from "./../../grid/otherField.vue";
import gridChosen from "./chosen.vue";
import worksheetRun from "@/pages/system/zerocode/run/worksheet";
import { mapGetters } from "vuex";
import {
  findCorrelationRows,
  findCorrelationDefault,
  businessData,
  findById,
  gridCustomFindByKey,
  gridCustomSave,
} from "@/services/system/zerocode/run/edit";
export default {
  components: {
    einput: gridInput,
    etextarea: gridTextarea,
    eswitch: gridSwitch,
    eenumber: gridNumber,
    eeradio: gridRadio,
    eeselect: gridSelect,
    eecheckbox: gridCheckbox,
    esys: gridSys,
    eserialNo: gridSerialNo,
    edate: gridDate,
    eotherField: gridOtherField,
    gridChosen,
    worksheetRun,
  },
  computed: {
    ...mapGetters("account", ["zeroCode"]),
  },
  data() {
    return {
      componentName: "", //组件名称
      grid: {
        loading: true,
      },
      columns: [],

      //编辑组件
      worksheetRun: {
        rowId: newGuid(),
        visible: false,
      },

      //选择
      chosen: {
        rowIds: [],
        visible: false,
      },

      /**
       * 列表自定义选项
       */
      gridCustom: {
        fixedData: null,
        resizableData: null,
        sortData: null,
        visibleData: null,
      },
    };
  },
  props: ["record", "value", "formValue", "parentDisabled", "worksheet"],
  watch: {
    "record.options.columns": {
      handler: function (newVal, oldVal) {
        if (newVal.length != oldVal.length) {
          this.initColumn();
        }
      },
      deep: true,
    },
    "record.options.zeroCodeId": {
      handler: function (val, oldVal) {
        if (val != oldVal) {
          this.initGridOption();
          this.initGridData();
        }
      },
      deep: true,
    },
  },
  created() {
    this.initGridOption();
    this.initGridData();
  },
  methods: {
    /**
     * 更改值状态
     */
    updateStatus({ row, column }) {
      let that = this;
      this.$refs[this.record.key].updateStatus({ row, column });
      //更新关联字段值
      businessData({
        zeroCodeId: that.record.options.zeroCodeId,
        rowId: row.RowId,
        values: JSON.stringify([
          {
            key: column.field,
            value: row[column.field],
          },
        ]),
      }).then(function (result) {
        if (result.code == that.eipResultCode.success) {
        } else {
          that.$message.error(result.msg);
        }
      });
      this.handleInput();
    },

    /**
     * 改变事件
     */
    handleInput() {
      this.$emit("change", this.grid.data);
    },

    /**
     *
     */
    getOptions(field) {
      return this.$utils.find(
        this.record.options.columns,
        (f) => f.key == field
      );
    },
    /**
     *初始化列表配置项
     */
    initGridOption() {
      let that = this;
      let zeroCodeId = this.record.options.zeroCodeId;
      this.grid = {
        id: "correlation-grid",
        editConfig: {
          trigger: "click",
          mode: "cell",
        },
        maxHeight: "300",
        loading: true,
        seqConfig: {},
        pagerConfig: {},
        printConfig: {},
        exportConfig: {},
        filterConfig: {
          remote: true,
        },
        customConfig: {
          storage: true,
          mode: "popup",
          restoreStore({ storeData }) {
            return true;
          },
          updateStore({ id, type, storeData }) {
            let resizableData = that.$utils.merge(
              that.gridCustom.resizableData,
              storeData.resizableData
            );
            let fixedData = that.$utils.merge(
              that.gridCustom.fixedData,
              storeData.fixedData
            );
            let sortData = that.$utils.merge(
              that.gridCustom.sortData,
              storeData.sortData
            );
            let visibleData = that.$utils.merge(
              that.gridCustom.visibleData,
              storeData.visibleData
            );
            gridCustomSave({
              key: zeroCodeId + "_" + that.record.key,
              title: that.record.label,
              config: JSON.stringify({
                fixedData: fixedData,
                resizableData: resizableData,
                sortData: sortData,
                visibleData: visibleData,
              }),
            }).then((result) => {});
            return true;
          },
        },
        sortConfig: {
          trigger: "cell",
          defaultSort: {},
          orders: ["desc", "asc", null],
          remote: true,
          multiple: true,
          chronological: true,
        },
        toolbarConfig: {
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools",
          },
        },
        columns: [],
        data: [],
        extend: {
          id: null,
        },
      };
      //判断是否
      this.initColumn();
    },

    /**
     * 初始化列
     */
    async initColumn() {
      let that = this;
      this.grid.columns = [];

      let columns = [];
      //获取

      var systemZeroCodeData = that.$utils.find(
        this.zeroCode,
        (f) => f.zeroCodeId == this.record.options.zeroCodeId
      );
      if (!systemZeroCodeData) {
        systemZeroCodeData = (await findById(this.record.options.zeroCodeId))
          .data;
      }

      that.columns = JSON.parse(systemZeroCodeData.columnJson);
      that.columns
        .filter((f) => that.record.options.columns.includes(f.key))
        .forEach((element) => {
          let column = {
            field: element.key,
            title: element.label,
            width: element.width,
            sortable: true,
            slots: {
              edit: "edit",
            },
            editRender: {
              enabled: that.record.options.canEdit,
            },
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          };
          var sysFind = that.$utils.find(
            that.eipSystemFiled,
            (f) => f.key == element.key
          );
          if (sysFind) {
            //判断是否为系统字段
            switch (element.key) {
              case "CreateTime":
              case "UpdateTime":
                column.filters = [
                  {
                    data: {
                      type: "datetime",
                      op: "cn",
                      write: null,
                      min: null,
                      max: null,
                    },
                  },
                ];
                columns.push(column);
                break;
              case "RowId":
                column.filters = [
                  {
                    data: {
                      type: "input",
                      key: null,
                      op: "cn",
                      write: null,
                      options: [],
                    },
                  },
                ];
                columns.push(column);
                break;
              case "CreateUser":
              case "UpdateUser":
                column.filters = [
                  {
                    data: {
                      type: "user",
                      op: "cn",
                      write: null,
                    },
                  },
                ];
                column.slots.default = "default";
                columns.push(column);
                break;
            }
          } else {
            switch (element.type) {
              case that.eipZeroCodeControl.radio:
              case that.eipZeroCodeControl.checkbox:
              case that.eipZeroCodeControl.select:
                let options = [];
                element.options.options.forEach((item) => {
                  options.push({
                    value: item.value,
                    label: item.label,
                    checked: false,
                    color: element.options.optionsColor ? item.color : null,
                  });
                });
                column.filters = [
                  {
                    data: {
                      type: "select",
                      key: null,
                      op: "jcn",
                      write: null,
                      options: options,
                    },
                  },
                ];
                break;
              case that.eipZeroCodeControl.number:
                column.filters = [
                  {
                    data: {
                      type: "number",
                      op: "cn",
                      write: null,
                      min: null,
                      max: null,
                    },
                  },
                ];
                break;
              case that.eipZeroCodeControl.switch:
                column.filters = [
                  {
                    data: {
                      type: "switch",
                      key: null,
                      op: "cn",
                      write: null,
                      options: [
                        {
                          value: 1,
                          label: "是",
                          checked: false,
                          color: "red",
                        },
                        {
                          value: 0,
                          label: "否",
                          checked: false,
                          color: "#1890ff",
                        },
                      ],
                    },
                  },
                ];
                break;
              case that.eipZeroCodeControl.rate:
                column.filters = [
                  {
                    data: {
                      type: "number",
                      op: "cn",
                      write: null,
                      min: null,
                      max: null,
                    },
                  },
                ];
                break;
              case that.eipZeroCodeControl.slider:
                column.filters = [
                  {
                    data: {
                      type: "number",
                      op: "cn",
                      write: null,
                      min: null,
                      max: null,
                    },
                  },
                ];
                break;
              case that.eipZeroCodeControl.uploadFile:
              case that.eipZeroCodeControl.uploadImg:
                break;
              case that.eipZeroCodeControl.editor:
                column.type = "html";
                break;
              case that.eipZeroCodeControl.date:
                column.filters = [
                  {
                    data: {
                      type: "datetime",
                      op: "cn",
                      write: null,
                      min: null,
                      max: null,
                    },
                  },
                ];
                break;
            }
            if (element.type != that.eipZeroCodeControl.editor) {
              column.slots.default = "default";
            }
            columns.push(column);
          }
        });

      //获取grid
      var gridCustom = await gridCustomFindByKey(
        this.record.options.zeroCodeId + "_" + this.record.key
      );
      if (gridCustom.data != null && gridCustom.data.config != null) {
        var config = JSON.parse(gridCustom.data.config);
        if (config.resizableData) {
          var resizableDataKey = that.$utils.keys(config.resizableData);
          resizableDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.width = config.resizableData[key];
            }
          });
          that.gridCustom.resizableData = config.resizableData;
        }
        //固定
        if (config.fixedData) {
          var fixedDataKey = that.$utils.keys(config.fixedData);
          fixedDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.fixed = config.fixedData[key];
            }
          });
          that.gridCustom.fixedData = config.fixedData;
        }
        //隐藏显示
        if (config.visibleData) {
          var visibleDataKey = that.$utils.keys(config.visibleData);
          visibleDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.visible = config.visibleData[key];
            }
          });
          that.gridCustom.visibleData = config.visibleData;
        }
        let cloneColumns = [];
        //顺序
        var sortDataKey = that.$utils.keys(config.sortData);
        if (config.sortData && sortDataKey.length > 0) {
          let sortArray = [];
          sortDataKey.forEach((key) => {
            sortArray.push({
              key: key,
              value: config.sortData[key],
            });
          });
          sortArray = that.$utils.orderBy(sortArray, "value");
          sortArray.forEach((sort) => {
            var columnsFind = that.$utils.find(
              columns,
              (f) => f.field == sort.key
            );
            if (columnsFind) {
              cloneColumns.push(columnsFind);
            }
          });
          columns = cloneColumns;
          that.gridCustom.sortData = config.sortData;
        }
      }
      columns.unshift({
        type: "seq",
        width: 50,
        fixed: "left",
        resizable: false,
        slots: {
          header: "seq",
        },
      });
      columns.unshift({
        title: "操作",
        field: "operate",
        width: 50,
        align: "center",
        fixed: "left",
        slots: {
          default: "operate",
        },
      });

      columns.unshift({
        type: "checkbox",
        width: 50,
        align: "center",
        fixed: "left",
        resizable: false,
        slots: {
          checkbox: "checkbox",
          header: "checkboxHeader",
        },
      });

      that.grid.columns = columns;

      setTimeout(function () {
        that.grid.loading = false;
      }, 100);
    },

    /**
     *
     */
    cellStyle({ row }) {
      let option = this.record.options;
    },

    /**
     * 新增
     */
    add() {
      this.worksheetRun.visible = true;
    },
    /**
     *
     */
    chosenClick() {
      this.chosen.rowIds = this.grid.data.map((m) => m.RowId);
      this.chosen.visible = true;
    },
    /**
     *
     */
    worksheetRunOk(result) {
      const data = {};
      var showColumns = this.columns.filter((f) =>
        this.record.options.columns.includes(f.key)
      );
      for (let index = 0; index < showColumns.length; index++) {
        const item = showColumns[index];
        data[item.key] = result.data[item.key];
      }
      this.grid.data.push({
        ...data,
        RowId: result.data.RowId,
      });
      //数据源获取
      this.handleInput();
      this.worksheetRun.visible = false;
    },

    /**
     *
     * @param data
     */
    chosenOk(data) {
      let that = this;
      data.forEach((item) => {
        //判断是否已选
        var check = that.$utils.find(
          that.grid.data,
          (f) => f.RowId == item.RowId
        );
        if (!check) {
          that.worksheetRunOk({
            data: item,
          });
        }
      });
    },

    /**
     * 移除
     * @param {*} item
     */
    remove(item) {
      const index = this.grid.data.indexOf(item);
      if (index !== -1) {
        this.grid.data.splice(index, 1);
      }
      //数据源获取
      this.handleInput();
    },

    /**
     * 清除
     */
    clear() {
      let that = this;
      let nowChosen = this.$refs[this.record.key].getCheckboxRecords(true);
      //获取其他页显示项
      let otherChosen =
        this.$refs[this.record.key].getCheckboxReserveRecords(true);
      var data = nowChosen.concat(otherChosen);
      //判断是否选择了数据
      if (data.length == 0) {
        this.$message.error("请选择数据");
        return;
      }
      data.forEach((item) => {
        that.remove(item);
      });
    },

    /**
     * 复制数据
     * @param {*} record
     */
    copy(record) {
      const data = {};
      var showColumns = this.columns.filter((f) =>
        this.record.options.columns.includes(f.key)
      );
      showColumns.forEach((item) => {
        data[item.key] = record[item.key];
      });
      const index = this.grid.data.indexOf(record);
      data.RowId = newGuid();
      this.grid.data.splice(index + 1, 0, data);
      this.handleInput();
    },

    /**
     * 初始化数据
     */
    initGridData() {
      let that = this;
      if (this.worksheet.mode == this.eipZeroCodeWorkSheetMode.edit) {
        findCorrelationRows({
          zeroCodeId: this.worksheet.zeroCodeId,
          key: this.record.key,
          rowId: this.worksheet.rowId,
        }).then((resultTable) => {
          resultTable.data.data.forEach((res) => {
            that.grid.data.push(res);
          });
          that.handleInput();
        });
      } else if (this.worksheet.mode == this.eipZeroCodeWorkSheetMode.button) {
        findCorrelationRows({
          zeroCodeId: this.worksheet.zeroCodeId,
          key: this.record.key,
          rowId: this.worksheet.rowId,
        }).then((resultTable) => {
          resultTable.data.data.forEach((res) => {
            that.grid.data.push(res);
          });
          that.handleInput();
        });
      } else if (this.worksheet.mode == this.eipZeroCodeWorkSheetMode.add) {
        //获取默认值
        findCorrelationDefault({
          zeroCodeId: this.worksheet.zeroCodeId,
          key: this.record.key,
        }).then((resultTable) => {
          resultTable.data.data.forEach((res) => {
            that.grid.data.push(res);
          });
        });
      }
    },
  },
};
</script>
<style lang="less" scoped></style>
